﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace AutomaticScrewLocking.domain.torque.dataStorage.service.impl
{
    /// <summary>
    /// 数据存储服务实现类-CSV格式
    /// </summary>
    public class CsvDataStorageServiceImpl : DataStorageService
    {

        /// <summary>
        /// 存储最大扭力数据，保存为CSV文件
        /// </summary>
        /// <param name="maxTorque">最大扭力</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool SaveMaxTorqueData(double maxTorque, out string errorMsg)
        {
            bool result = false;
            errorMsg = string.Empty;
            try
            {
                string dir = Path.Combine(Application.StartupPath, "Data");
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                string fileName = DateTime.Now.ToString("yyyyMMdd") + ".csv";
                string fileFullPath = Path.Combine(dir, fileName);

                if (!File.Exists(fileFullPath))
                {
                    using (StreamWriter sw = new StreamWriter(fileFullPath, false, Encoding.UTF8))
                    {
                        sw.WriteLine("时间,最大扭力");
                    }
                }

                using (StreamWriter sw = new StreamWriter(fileFullPath, true, Encoding.UTF8))
                {
                    string content = $"{DateTime.Now.ToString()},{maxTorque}";
                    sw.WriteLine(content);
                }
                result = true;
            }
            catch(Exception ex)
            {
                errorMsg = ex.Message;
            }

            return result;
        }

        public List<double> getHistoryTorqueListByTime(DateTime startTime, DateTime endTime)
        {
            return null;
        }
    }
}
